package com.qf.user.factory.registerfactory;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.User;
import com.qf.common.core.exception.CustomerException;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.user.mapper.UserMapper;
import com.qf.user.param.RegisterParam;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zdl
 * @date 2025/3/22
 */
@Service
public class PhoneAndVerificationCodeRegistration implements Registration {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public int register(RegisterParam registerParam) { //必传参数：phone，code,type=2
        // 校验手机号是否已注册
        List<User> u = userMapper.selectList(Wrappers.lambdaQuery(User.class).eq(User::getPhone, registerParam.getPhone()));
        if (!u.isEmpty()) {
            throw new CustomerException("5001", "当前手机号已注册");
        }
        //获取验证码
        String cachePhone = redisUtil.getCacheObject(registerParam.getPhone());
        if (cachePhone == null) {
            throw new CustomerException("3002", "验证码已过期");
        }
        if (!cachePhone.equals(registerParam.getCode())) {
            throw new CustomerException("3003", "验证码错误");
        }
        //注册
        User user1 = new User();
        //手机号注册 默认密码123456
        user1.setPassword(SecureUtil.md5("123456"));
        user1.setPhone(registerParam.getPhone());
        return userMapper.insert(user1) == 1 ? 1 : 0;
    }
}
